#define _LARGEFILE_SOURCE
#define _LARGEFILE64_SOURCE
#define _FILE_OFFSET_BITS 64
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/msg.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#include <sys/stat.h>
#include <pthread.h>
#include <fcntl.h>
#include <ctype.h>
#include "interface_emum.h"
#include "log.h"
#include "data_handle_lib.h"
#include "ipc_node.h"
#include "usr_xdma.h"

#define LOG_TAG "test_debug_named_pipe.c :"

#define DEBUG_NAMED_PIPE_PATH   "/tmp/debug_named_pipe_for_c2h"

static int pipe_fd = -1;

typedef struct
{
    long int msg_type;
    data_block_str block;
} msg_st_slow_port;

static void sigfunc(int sig)
{
    LOG("recv a sig = %d,do clean flow!\r\n", sig);
    close(pipe_fd);
    LOG("terminal the programme!\r\n");
    exit(1);
}

int main(int argc, char **argv)
{
    int ret_val = -1, i = 0, j = 0;
    msg_st_slow_port t_data_blk;

    sig_t sighandler;

    sighandler = signal(SIGINT, sigfunc);
    if (sighandler == SIG_ERR)
    {
        LOGE(LOG_TAG"signal error,errno = %d\r\n", errno);
        goto err_out;
    }

    memset(t_data_blk.block.block, 'a', DEFAULT_MSG_SIZE);

    pipe_fd = open(DEBUG_NAMED_PIPE_PATH, O_RDWR);
    if (pipe_fd < 0)
    {
        LOGE(LOG_TAG"open pipe failed,errno = %d\r\n", errno);
        ret_val = pipe_fd;
        goto err_out;
    }

    i = 0;
    j = 10;
    while (1)
    {
        memset(t_data_blk.block.block, 'a', DEFAULT_MSG_SIZE);
        t_data_blk.msg_type = i++;
        t_data_blk.block.block_size = j++;
        if (j >= 4096) j = 10;
        t_data_blk.block.block[50] = '\0';
        i = i % ENMUM_RESERVE;
        ret_val = write(pipe_fd, &t_data_blk, sizeof(msg_st_slow_port));
        if (ret_val < 0)
        {
            LOGE(LOG_TAG"write pipe failed,errno = %d\r\n", errno);
            goto err_out;
        }
        usleep(1000000);
    }

err_out:
    if (pipe_fd >= 0)
    {
        close(pipe_fd);
        pipe_fd = -1;
    }

    return ret_val;
}
